<template>
  <div>
    <div class="query-form">
      <query-form :form="form" v-model="dataForm" @handleQuery="handleQuery" />

      <!-- <el-form :inline="true" ref="form" :model="dataForm">
        <el-form-item label="用户ID：" prop="userId">
          <el-input
            v-model="dataForm.userId"
            placeholder="请输入用户ID"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称：" prop="userName">
          <el-input
            v-model="dataForm.userName"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="state">
          <el-select v-model="dataForm.state" placeholder="请选择">
            <el-option
              v-for="(item, index) in querySelectArr"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form> -->
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleCreate">新增</el-button>
        <el-button type="danger" @click="handlePatchDel">批量删除</el-button>
      </div>
      <el-table :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="index" width="50" label="序号" align="center" />
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(item, index) in tableFields"
          :key="index"
          :label="item.label"
          :prop="item.prop"
          :min-width="item.minWith"
          :formatter="item.formatter"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        :total="pager.total"
        :current-page="pager.pageNum"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
      ></el-pagination>
    </div>

    <el-dialog
      :title="action == 'add' ? '用户新增' : '用户编辑'"
      v-model="showModal"
    >
      <el-form
        ref="dialogForm"
        :model="userForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="userForm.userName"
            :disabled="action == 'edit'"
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            v-model="userForm.userEmail"
            :disabled="action == 'edit'"
            placeholder="请输入用户邮箱"
          >
            <!-- <template #append>@163.com</template> -->
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="userForm.job" placeholder="请输入岗位" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state" style="width: 100%">
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select
            v-model="userForm.roleList"
            placeholder="请选择用户系统角色"
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role._id"
              :label="role.roleName"
              :value="role._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            v-model="userForm.deptId"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, toRaw } from 'vue'
import utils from "../../utils/utils";
import queryForm from '../../../packages/QueryForm/queryForm.vue';

export default {
  components: { queryForm },
  setup () {
    console.log(getCurrentInstance())
    const { ctx, appContext } = getCurrentInstance()
    const that = appContext.config.globalProperties
    const dataForm = reactive({
      userId: '',
      userName: '',
      state: 1,
    })
    const querySelectArr = [
      { label: '所有', value: 0 },
      { label: '在职', value: 1 },
      { label: '离职', value: 2 },
      { label: '试用期', value: 3 },
    ];
    const form = [
      {
        type: 'input',
        label: '用户ID',
        model: 'userId',
        placeholder: '请输入用户ID'
      },
      {
        type: 'input',
        label: '用户名称',
        model: 'userName',
        placeholder: '请输入用户名称'
      },
      {
        type: 'select',
        label: '状态',
        model: 'state',
        placeholder: '请选择',
        options: querySelectArr
      },
    ]
    // 定义表单校验规则
    const rules = reactive({
      userName: [
        {
          required: true,
          message: "请输入用户名称",
          trigger: "blur",
        },
      ],
      userEmail: [
        { required: true, message: "请输入用户邮箱", trigger: "blur" },
      ],
      mobile: [
        {
          pattern: /1[3-9]\d{9}/,
          message: "请输入正确的手机号格式",
          trigger: "blur",
        },
      ],
      deptId: [
        {
          required: true,
          message: "请选择部门角色",
          trigger: "blur",
        },
      ],
    });
    // 定义动态表格-格式
    const tableFields = [
      { prop: 'userId', label: '用户ID', minWidth: 100 },
      { prop: 'userName', label: '用户名', minWidth: 120 },
      { prop: 'userEmail', label: '用户邮箱', minWidth: 120 },
      { prop: 'role', label: '用户角色', minWidth: 100 },
      {
        prop: 'state', label: '用户状态', minWidth: 100,
        formatter: (row, column, value) => {
          let val = value
          querySelectArr.map(v => {
            if (v.value == value) {
              val = v.label
            }
          });
          return val
        },
      },
      {
        prop: 'createTime', label: '注册时间', minWidth: 140,
        formatter: (row, column, value) => {
          return utils.formateDate(new Date(value));
        },
      },
      {
        prop: 'lastLoginTime', label: '最后登录时间', minWidth: 140,
        formatter: (row, column, value) => {
          // console.log(row, column, value)
          // console.log(utils.formateDate(new Date(value)))
          return utils.formateDate(new Date(value));
        },
      },
    ];

    const dataList = ref([])
    const pager = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })

    // 获取用户列表
    const getUserList = async () => {
      let params = { ...dataForm, ...pager };
      try {
        const { list, page } = await that.$api.getUserList(params);
        dataList.value = list;
        pager.total = page.total;
      } catch (error) { }
    };
    //  查询事件，获取用户列表
    const handleQuery = (values) => {
      console.log(values)
      // debugger;
      for (let k in values) {
        dataForm[k] = values[k]
      }
      getUserList();
    };
    // 重置查询表单
    const handleReset = (form) => {
      ctx.$refs[form].resetFields();
    };
    // 分页事件处理
    const handleCurrentChange = (current) => {
      pager.pageNum = current;
      getUserList();
    };
    // 用户单个删除
    const handleDel = async (row) => {
      await that.$api.userDel({
        userIds: [row.userId], //可单个删除，也可批量删除
      });
      that.$message.success("删除成功");
      getUserList();
    };
    // 批量删除
    const handlePatchDel = async () => {
      if (checkedUserIds.value.length == 0) {
        that.$message.error("请选择要删除的用户");
        return;
      }
      const res = await that.$api.userDel({
        userIds: checkedUserIds.value, //可单个删除，也可批量删除
      });
      if (res.nModified > 0) {
        that.$message.success("删除成功");
        getUserList();
      } else {
        that.$message.error("修改失败");
      }
    };

    // 表格多选
    const handleSelectionChange = (list) => {
      let arr = [];
      list.map((item) => {
        arr.push(item.userId);
      });
      checkedUserIds.value = arr;
    };

    // 用户新增
    // 选中用户列表对象
    const checkedUserIds = ref([]);
    // 弹框显示对象
    const showModal = ref(false);
    // 新增用户Form对象
    const userForm = reactive({
      state: 1,
    });
    // 所有角色列表
    const roleList = ref([]);
    // 所有部门列表
    const deptList = ref([]);
    // 定义用户操作行为
    const action = ref("add");
    const handleCreate = () => {
      action.value = "add";
      userForm.state = 1;
      showModal.value = true;
    };

    const getDeptList = async () => {
      let list = await that.$api.getDeptList();
      deptList.value = list;
    };

    // 角色列表查询
    const getRoleList = async () => {
      let list = await that.$api.getRoleList1();
      roleList.value = list;
    };
    // 用户弹窗关闭
    const handleClose = () => {
      showModal.value = false;
      handleReset("dialogForm");
    };
    // 用户提交
    const handleSubmit = () => {
      ctx.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          let params = toRaw(userForm);
          // params.userEmail += "@imooc.com";
          params.action = action.value;
          let res = await that.$api.userSubmit(params);
          showModal.value = false;
          if (action.value == 'edit') {
            that.$message.success("用户编辑成功");
          } else {
            that.$message.success("用户创建成功");
          }
          handleReset("dialogForm");
          getUserList();
        }
      });
    };
    // 用户编辑
    const handleEdit = (row) => {
      action.value = "edit";
      showModal.value = true;
      ctx.$nextTick(() => {
        Object.assign(userForm, row);
      });
    };


    onMounted(() => {
      getUserList();
      getDeptList();
      getRoleList();
    })
    return {
      form,
      pager,
      dataForm,
      querySelectArr,
      tableFields,
      dataList,
      handleQuery,
      handleReset,
      handleCurrentChange,
      handleDel,
      handlePatchDel,
      handleSelectionChange,
      rules, //
      showModal,
      userForm,
      roleList,
      deptList,
      action,
      handleCreate,
      handleClose,
      handleSubmit,
      handleEdit,
    }
  },
  methods: {
    handleReset (formName) {
      this.$refs[formName].resetFields()
    },
  }
}
</script>

<style lang="scss" scoped>
</style>
